﻿using System.Collections.Generic;
using System.Xml.Linq;
using System.Linq;
using EbbinghausWord.Entities;

namespace EbbinghausWord.BLL
{
    /// <summary>
    /// 词典管理类
    /// </summary>
    public class DictionaryManager
    {
        #region private filed

        /// <summary>
        /// 单词词典
        /// </summary>
        private static Dictionary<string, DictionaryWord> _wordDictionary = null;

        #endregion


        #region public method

        /// <summary>
        /// 初始化词典
        /// </summary>
        /// <returns></returns>
        public static void InitDictionary()
        {
            _wordDictionary = new Dictionary<string, DictionaryWord>();

            //打开词典文件
            var works = XElement.Load(SystemConfig.DictionaryFileName);

            //初始化词典
            foreach (var xElement in works.Elements())
            {
                var word = DictionaryWord.FromTable(xElement);
                //var word = new DictionaryWord();

                //if (xElement.Element("word") != null)
                //    word.English = xElement.Element("word").Value.Trim();

                //if (xElement.Element("trans") != null)
                //    word.Chinese = xElement.Element("trans").Value.Trim();

                //if (xElement.Element("phonetic") != null)
                //    word.Soundmark = xElement.Element("phonetic").Value.Trim();

                _wordDictionary.Add(word.English, word);
            }

            _wordDictionary = _wordDictionary.OrderBy(x => x.Key).ToDictionary(x => x.Key, y => y.Value);
        }

        /// <summary>
        /// 根据词典 Id  获得对应词典
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, DictionaryWord> GetWordDictionary()
        {
            if (_wordDictionary == null)
                InitDictionary();
            return _wordDictionary;
        }

        #endregion
    }
}
